// 2025/9/18
// 生命游戏

class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size(), n = board[0].size();
        vector<vector<int>> living(m, vector<int>(n, 0));
        auto isValid = [m, n](int x, int y){
            return (x >= 0 && x < m && y >= 0 && y < n);
        };

        vector<pair<int, int>> dpos = {{-1, -1}, {-1, 0}, {-1, 1}, 
            {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}
        };
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                for(auto& pr : dpos)
                {
                    int x = i + pr.first, y = j + pr.second;
                    if(isValid(x, y) && board[x][y] == 1)
                        living[i][j]++;
                }
            }
        }

        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(living[i][j] > 3 || living[i][j] < 2)
                    board[i][j] = 0;
                if(living[i][j] == 3)
                    board[i][j] = 1;
            }
        }
    }
};